package com.hhit.zhgd.controller

import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.metadata.IPage
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.hhit.zhgd.component.FileProperties
import com.hhit.zhgd.domain.dto.BackStageDrawingSupplyPlanDTO
import com.hhit.zhgd.domain.dto.CakeInfo
import com.hhit.zhgd.domain.entity.ZhgdDrawingSupplyPlan
import com.hhit.zhgd.domain.response.BaseResp
import com.hhit.zhgd.service.ZhgdDrawingSupplyPlanService
import jakarta.annotation.Resource
import jakarta.servlet.http.HttpServletResponse
import org.apache.commons.lang3.StringUtils
import org.springframework.util.ObjectUtils
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.util.function.Consumer
import javax.validation.Valid

@RestController
class ZhgdDrawingSupplyPlanController {

    @Resource
    private val zhgdDrawingSupplyPlanService: ZhgdDrawingSupplyPlanService? = null

    @Resource
    private val fileProperties: FileProperties? = null

    @PostMapping("backStage/importDrawingSupplyPlan")
    @Throws(Exception::class)
    fun importDrawingSupplyPlan(@RequestParam("file") multipartFile: MultipartFile?): BaseResp<Any?>? {
        return zhgdDrawingSupplyPlanService!!.importDrawingSupplyPlan(multipartFile)
    }

    @GetMapping("getDrawingSupplyPlans")
    fun getDrawingSupplyPlans(
        @RequestParam(name = "volumeNumber", defaultValue = "") volumeNumber: String?,
        @RequestParam(name = "volumeName", defaultValue = "") volumeName: String?,
        @RequestParam(name = "page", defaultValue = "1") page: Int,
        @RequestParam(name = "size", defaultValue = "15") size: Int
    ): BaseResp<Any?>? {
        val pageInfo = Page<ZhgdDrawingSupplyPlan>(page.toLong(), size.toLong())
        val queryWrapper =
            QueryWrapper<ZhgdDrawingSupplyPlan>().like(StrUtil.isNotBlank(volumeNumber), "volume_number", volumeNumber)
                .or().like(StrUtil.isNotBlank(volumeName), "volume_name", volumeName)
        return BaseResp.success(zhgdDrawingSupplyPlanService?.page(pageInfo, queryWrapper))
    }

    /**
     * @描述 确认 交图
     * @参数 [id]
     * @返回值 com.hhit.zhgd.utils.R
     * @创建人 qianchengcheng
     * @创建时间 2023/7/24
     * @修改人和其它信息
     */
    @GetMapping("confirmHandInDrawings")
    fun confirmHandInDrawings(@RequestParam("id") id: Int?): BaseResp<Any?>? {
        return zhgdDrawingSupplyPlanService?.confirmHandInDrawings(id)
    }


    /**
     * @param info 查询实体
     * @return Result
     */
    @PostMapping("/getDrawing")
    fun page(@RequestBody info: ZhgdDrawingSupplyPlan): BaseResp<Any?>? {
        val pageInfo: Page<ZhgdDrawingSupplyPlan> = Page(info.page!!.toLong(), info.size!!.toLong())
        val wrapper = QueryWrapper<ZhgdDrawingSupplyPlan>()
        wrapper.like(!ObjectUtils.isEmpty(info.stage), "stage", info.stage)
        wrapper.like(!ObjectUtils.isEmpty(info.volumeName), "volume_name", info.volumeName)
        wrapper.like(!ObjectUtils.isEmpty(info.volumeNumber), "volume_number", info.volumeNumber)
        wrapper.like(
            !ObjectUtils.isEmpty(info.volumeClassify),
            "volume_classify",
            info.volumeClassify
        )
        wrapper.orderByDesc("id")
        val page: IPage<ZhgdDrawingSupplyPlan> = zhgdDrawingSupplyPlanService!!.page(pageInfo, wrapper)
        return BaseResp.success(page)
    }

    /**
     * @param info 查询实体
     * @return Result
     */
    @PostMapping("/addDrawing")
    fun add(@RequestBody info: ZhgdDrawingSupplyPlan): BaseResp<Any?>? {
        zhgdDrawingSupplyPlanService?.save(info)
        return BaseResp.success()
    }

    /**
     * @description 后台管理-进度管理-新增图纸供应计划
     * @author qianchengcheng
     * @date 2024/6/28 10:54
     */
    @PostMapping("backStage/addDrawing")
    fun addDrawing(
        @RequestBody backStageDrawingSupplyPlanDTO: @Valid BackStageDrawingSupplyPlanDTO?,
        bindingResult: BindingResult
    ): BaseResp<Any?>? {
        //判断有没有异常错误,如果有则返回默认消息
        if (bindingResult.hasErrors()) {
            val defaultMessage = bindingResult.fieldError?.defaultMessage
            return BaseResp.fail(defaultMessage)
        }
        return zhgdDrawingSupplyPlanService?.addDrawing(backStageDrawingSupplyPlanDTO)
    }

    /**
     * @description 后台管理-进度管理-修改图纸供应计划
     * @author qianchengcheng
     * @date 2024/6/28 11:07
     */
    @PostMapping("backStage/editDrawing")
    fun editDrawing(
        @RequestBody backStageDrawingSupplyPlanDTO: BackStageDrawingSupplyPlanDTO?,
        bindingResult: BindingResult
    ): BaseResp<Any?>? {
        if (bindingResult.hasErrors()) {
            val defaultMessage = bindingResult.fieldError?.defaultMessage
            return BaseResp.fail(defaultMessage)
        }
        return zhgdDrawingSupplyPlanService?.editDrawing(backStageDrawingSupplyPlanDTO)
    }

    @GetMapping("backStage/delDrawing")
    fun delDrawing(@RequestParam("ids") ids: List<Int?>?): BaseResp<Any?>? {
        return zhgdDrawingSupplyPlanService?.delDrawing(ids)
    }

    @GetMapping("backStage/getDrawingPageInfo")
    fun getDrawingPageInfo(
        @RequestParam(name = "keyWord") keyWord: String?,
        @RequestParam(name = "page", defaultValue = "1") page: Int,
        @RequestParam(name = "size", defaultValue = "15") size: Int
    ): BaseResp<Any?>? {
        return BaseResp.success(zhgdDrawingSupplyPlanService?.getDrawingPageInfo(keyWord, page, size))
    }

    /**
     * @description 后台管理-进度管理-导出图纸供应计划
     * @author qianchengcheng
     * @date 2024/7/3 17:18
     */
    @GetMapping("backStage/exportDrawingPlan")
    fun exportDrawingPlan(response: HttpServletResponse?) {
        try {
            zhgdDrawingSupplyPlanService?.exportDrawingPlan(response)
        } catch (e: Exception) {
            e.printStackTrace()
//            log.error("exportDrawingPlan==>导出图纸供应计划异常", e)
        }
    }

    /**
     * @param info 查询实体
     * @return Result
     */
    @PostMapping("/editDrawing")
    fun edit(@RequestBody info: ZhgdDrawingSupplyPlan): BaseResp<Any?>? {
        zhgdDrawingSupplyPlanService?.updateById(info)
        return BaseResp.success()
    }

    /**
     * @param info 查询实体
     * @return Result
     */
    @PostMapping("/delDrawing")
    fun del(@RequestBody info: ZhgdDrawingSupplyPlan): BaseResp<Any?>? {
        val list = zhgdDrawingSupplyPlanService?.list(
            QueryWrapper<ZhgdDrawingSupplyPlan>().`in`(
                "id",
                info.ids
            )
        )
        list?.forEach(Consumer { (_, _, _, _, _, _, _, _, _, _, drawUrl): ZhgdDrawingSupplyPlan ->
            if (StringUtils.isNotBlank(drawUrl)) {
                for (fileUrl in drawUrl?.split(",".toRegex())?.dropLastWhile { it.isEmpty() } ?: listOf()) {
                    val path: String = fileProperties?.parentPath + fileUrl
                    File(path).delete()
                }
            }
        })
        zhgdDrawingSupplyPlanService?.removeByIds(info.ids)
        return BaseResp.success()
    }

    @PostMapping("/totalDrawing")
    fun total(): BaseResp<Any?>? {
        val count = zhgdDrawingSupplyPlanService!!.count(null).toInt()
        val wra = LambdaQueryWrapper<ZhgdDrawingSupplyPlan>()
        wra.eq(ZhgdDrawingSupplyPlan::handInDrawingsFlag, 1)
        val countYes = zhgdDrawingSupplyPlanService.count(wra).toInt()
        val out: MutableList<CakeInfo> = ArrayList()
        out.add(CakeInfo(name = "应交付图纸", value = count))
        out.add(CakeInfo(name = "实际交付图纸", value = countYes))
        return BaseResp.success(out)
    }

}